package com.study.studyelasticsearch.util.es.extractor;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 提取检索结果中hit中的数据
 * @author 吴宇亮 on 2022/5/27 17:15
 */
@Service
public class EsHitExtractor<R> implements EsResultExtractor<R> {

    @Override
    public List<R> extract(SearchResponse searchResponse, Class<R> returnType) {
        SearchHits hits = searchResponse.getHits();
        List<R> result = new ArrayList<>(Long.valueOf(hits.getTotalHits().value).intValue());
        for (SearchHit hit : hits) {
            String sourceJson = hit.getSourceAsString();
            R bean = JSON.parseObject(sourceJson, returnType);
            result.add(bean);
        }
        return result;
    }

}
